<template>
	<div class="page-container">
		<el-row>
			<el-col>
				<h1>图片转Base64编码</h1>
				<el-form ref="form" :model="form">
					<el-form-item label="请选择要转换的图片文件">
						<el-upload ref="upload" class="upload-demo" action="" :show-file-list="false"
							:on-change="handleChange">
							<el-button size="medium" type="primary">选择文件</el-button>
							<div slot="tip" class="el-upload__tip">只能上传 png、jpg、jpeg、gif、bmp、svg、webp、tif 格式的图片</div>
						</el-upload>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="convertToBase64()">转换</el-button>
					</el-form-item>
					<el-form-item label="Base64编码结果：">
						<el-input type="textarea" id="base64Text" rows="10" readonly></el-input>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>
		
	</div>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					imageFile: null
				},
			};
		},
		methods: {
			handleChange(file) {
				this.form.imageFile = file.raw;
			},
			convertToBase64() {
				const file = this.form.imageFile;
				if (!file) {
					this.$message.error("请先选择要转换的图片文件！");
					return;
				}

				const reader = new FileReader();
				reader.onload = () => {
					let base64Text = reader.result.split(",")[1];
					const fileType = file.type.split("/")[1];
					base64Text = `data:image/${fileType};base64,${base64Text}`;
					document.getElementById("base64Text").value = base64Text;
				};
				reader.readAsDataURL(file);
			},
		},
	};
</script>


